package site.sorghum.ddl.mybatis.plus;

import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import site.sorghum.ddl.base.JavaCoreEntityGenerate;
import site.sorghum.ddl.entity.DdlColumnWrap;
import site.sorghum.ddl.entity.DdlTableWrap;
import site.sorghum.ddl.extra.ClassUtil;

import java.lang.reflect.Field;
import java.util.List;

/**
 * MybatisFlex实体生成器
 *
 * @author Sorghum
 */
public class MybatisPlusEntityGenerate extends JavaCoreEntityGenerate {

    @Override
    public DdlTableWrap get(Class<?> tClass) {
        DdlTableWrap coreDdlTableWrap = getCoreDdlTableWrap(tClass);
        TableName table = tClass.getAnnotation(TableName.class);
        if (table != null && table.value() != null && !table.value().isEmpty()) {
            coreDdlTableWrap.setName(table.value());
        }
        List<Field> fields = ClassUtil.fetchAllFields(tClass);
        for (Field field : fields) {
            DdlColumnWrap coreDdlColumnWrap = getCoreDdlColumnWrap(coreDdlTableWrap.getName(), field, coreDdlTableWrap.getPks());
            if (coreDdlColumnWrap == null) {
                continue;
            }
            TableField tableField = field.getAnnotation(TableField.class);
            if (tableField != null) {
                if (!tableField.exist()) {
                    continue;
                }
                if (tableField.value() != null && !tableField.value().isEmpty()) {
                    coreDdlColumnWrap.setName(tableField.value());
                }
            }
            TableId id = field.getAnnotation(TableId.class);
            if (id != null) {
                boolean contains = coreDdlTableWrap.getPks().contains(coreDdlColumnWrap.getName());
                if (!contains) {
                    coreDdlTableWrap.getPks().add(coreDdlColumnWrap.getName());
                }
            }
            coreDdlTableWrap.getColumns().add(coreDdlColumnWrap);
        }
        resort(coreDdlTableWrap.getColumns());
        return coreDdlTableWrap;
    }

}
